<?php

namespace addons\yunfood\model;

use addons\yunfood\library\ModelTrait;
use think\Exception;
use think\exception\PDOException;
use think\Model;

/**
 * 防重模型
 */
class Norepeat extends Model
{
    use ModelTrait;

    // 表名,不含前缀
    protected $name = 'yunfood_norepeat';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    protected $resultSetType = 'collection';

    /**
     * @param $scene
     * @param $value
     * @param false $return
     * @return bool
     * @throws Exception
     * @throws PDOException
     */
    public static function tryAddData($scene, $value, $return = false)
    {
        try {
            Norepeat::create(['scene' => $scene, 'value' => $value]);

            return true;
        } catch (PDOException $e) {
            if ($return) {
                return false;
            }
            if (strpos(strtolower($e->getMessage()), 'duplicate entry') !== false) {
                throw new Exception('数据重复，请稍后再试');
            }
            throw $e;
        }
    }
}
